// var that
class Tab {
  constructor(id) {
    this.main = document.querySelector(id)

    // that = this
    this.add = this.main.querySelector('.tabadd')
    // li的父元素
    this.ul = this.main.querySelector('.firstnav ul:first-child')
    this.fsection = this.main.querySelector('.tabscon')

    this.init()
  }

  updateNode() {
    this.lis = this.main.querySelectorAll('li')
    this.sections = this.main.querySelectorAll('section')
    // 删除获取叉号
    this.remove = this.main.querySelectorAll('.icon-guanbi')
    this.spans = this.main.querySelectorAll('.firstnav li span:first-child')
  }

  init() {
    this.updateNode()
    for (let i = 0; i < this.lis.length; i++) {
      this.lis[i].index = i
      // this.lis[i].onclick = this.toggleTab() //错误，不能加小括号
      this.lis[i].onclick = this.toggleTab.bind(this.lis[i], this)
      // c2 给X绑定点击事件
      this.remove[i].onclick = this.removeTab.bind(this.remove[i], this)
      this.spans[i].ondblclick = this.editTab
      this.sections[i].ondblclick = this.editTab
    }
    // console.log('this.add', this.add)
    // 添加
    this.add.onclick = this.addTab.bind(this.add, this)
  }

  toggleTab(that) {
    that.clearClass()
    // console.log('this', this)
    this.className = 'liactive'
    that.sections[this.index].className += ' conactive'
  }

  clearClass() {
    for (let i = 0; i < this.lis.length; i++) {
      this.lis[i].className = ''
      this.sections[i].className = ''
    }
  }

  /* addTab() {
    let li = `<li class="liactive"><span>测试1</span><span class="iconfont icon-guanbi"></span></li>`
    that.ul.insertAdjacentHTML('beforeend', li)
  } */
  addTab(that) {
    that.clearClass()
    var random = Math.random()
    let li = `<li class="liactive"><span>测试1</span><span class="iconfont icon-guanbi"></span></li>`
    var section = '<section class="conactive">测试 ' + random + '</section>'
    // b3,b4
    that.ul.insertAdjacentHTML('beforeend', li)
    // b7
    that.fsection.insertAdjacentHTML('beforeend', section)
    // b8
    that.init()
  }

  removeTab(that, e) {
    e.stopPropagation()

    let index = this.parentNode.index
    console.log(index)
    that.lis[index].remove()
    that.sections[index].remove()
    // c6
    that.init()
    if (document.querySelector('.liactive')) return
    index--
    that.lis[index] && that.lis[index].click()
  }

  editTab() {
    window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty()
    let str = this.innerHTML
    this.innerHTML = '<input type="text" />'
    let input = this.children[0]
    input.value = str
    input.select()
    input.onblur = function () {
      this.parentNode.innerHTML = this.value
    }
    input.onkeyup = function (e) {
      if (e.keyCode === 13) {
        this.blur()
      }
    }
  }
}

new Tab('#tab')
